package tp.tecnicasdisenio.job;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;

import tp.tecnicasdisenio.dao.impl.jdbc.MateriaDao;
import tp.tecnicasdisenio.model.entity.Materia;
import tp.tecnicasdisenio.model.mail.MailDownloader;

public class MailRetrieverJob implements Job {

  @Override
  public void execute(JobExecutionContext current) throws JobExecutionException {
    System.out.println("[CRON] " + new Date()
        + ": Entrando MailRetrieverJob."); // Change for a Logger.
    try {
      Scheduler scheduler = current.getScheduler();
      List<JobExecutionContext> executingJobs =
          scheduler.getCurrentlyExecutingJobs();
      int mailRetrievers = 0;
      for (JobExecutionContext context : executingJobs) {
        if (current.getJobInstance().getClass()
            .equals(context.getJobInstance().getClass())) {
          mailRetrievers++;
        }
      }
      if (executingJobs.size() > 1 && mailRetrievers > 1) {
        System.out.println("[CRON] MailRetrieverJob ya esta corriendo. " +
            "FIN DE LA EJECUCION.");
        return;
      }
      System.out.println("[CRON] MailRetrieverJob no esta corriendo. " +
          "CONTINUA...");
      MateriaDao materiaDao = MateriaDao.getInstance();
      ArrayList<Materia> todas = materiaDao.obtenerTodos();
      for (Materia materia : todas) {
        System.out.println("[CRON] Descargando mensajes de: "
            + materia.getCodigo() + " - " + materia.getNombre());
        MailDownloader.getMessages(true, materia);
      }
    } catch(SchedulerException e) {
      e.printStackTrace();
    }
    System.out.println("[CRON] " + new Date()
        + ": Cerrando MailRetrieverJob.");
  }
}
